from TinyShop17.CASE import LoginTinyShop
import re


class PayOrder:
    def __init__(self, orderid=128, paymentid=1, username='253775405@qq.com', password='yang130740',
                 url='http://192.168.10.139/ty17/TinyShop_v1.7'):
        self.session, result = LoginTinyShop.Login(username, password).start()
        print(result)
        self.url = url
        self.orderid = orderid
        self.paymentid = paymentid

    def payMoney(self):
        url = '%s/index.php?con=payment&act=dopay' % self.url
        data = {
            'order_id': self.orderid,
            'payment_id': self.paymentid,
            'channelBank': 'ICBC'
        }
        html = self.session.post(url, data=data).text
        passent = re.compile("value='(.*)'")
        self.content = passent.findall(html)

    def payBlance(self):
        url = '%s/index.php?con=payment&act=pay_balance' % self.url
        data = {
            'attach': self.content[0],
            'total_fee': self.content[1],
            'order_no': self.content[2],
            'return_url': self.content[3],
            'sign': self.content[4]
        }
        html = self.session.post(url, data=data).text
        passent = re.compile(r'<input type="hidden" name="attach" value="(.*)" />')
        content = passent.findall(html)[0]
        content = content.split('"')
        # print(content[0], content[6], content[12], content[18], content[24], content[30], content[36])
        url1 = '%s/index.php?con=payment&act=callback&payment_id=a.txt' % self.url
        data1 = {
            'attach': content[0],
            'total_fee': content[6],
            'order_no': content[12],
            'return_url': content[18],
            'order_status': content[24],
            'sign': content[30],
            'tiny_token_redirect': content[36]
        }
        self.html1 = self.session.post(url1, data=data1).text
        passent1 = re.compile(r'<i class="icon-order-0"></i>(.*) &nbsp;')
        buynumber = passent1.findall(self.html1)[0]
        print("订单编号： %s" % buynumber)

    def compile(self):
        if '支付成功，订购已完成' in self.html1:
            self.res = '支付成功'
        else:
            self.res = '支付失败'

    def start(self):
        try:
            self.payMoney()
            self.payBlance()
            self.compile()
        except Exception:
            self.res = '支付失败'
        return self.res


if __name__ == "__main__":
    PayOrder().start()
